let nodeEmail = require("../utils/node-connect-email");

/**
 * 用户注册
 * @param req
 * @param res
 * @param next
 * @return {Promise<void>}
 */
let register = async (req, res, next) => {
    const db = global.getDB();
    //解析req.body并存入到MongoDB数据库：user表
    let conditionJson = JSON.parse(req.body.conditionJson);
    let username = conditionJson.username;
    let password = conditionJson.password;
    try {
        db.collection('users').findOne({'username': username}).then(document => {
            if (!document) {
                db.collection('users').insertOne({'username': username, 'password': password});
                res.send({
                    success: true,
                    message: "注册成功",
                    status: 0,
                });
            } else {
                res.send({
                    success: false,
                    message: "该用户名已注册",
                    status: -1,
                });
            }
        })
    } catch (e) {
        console.log(e);
        res.send({
            success: false,
            message: '注册失败！',
            status: -1,
        });
    }
};

/**
 * 用户登录
 * @param req
 * @param res
 * @param next
 * @return {Promise<void>}
 */
let login = async (req, res, next) => {
    const db = global.getDB();
    //解析req.body并比较user表
    let conditionJson = JSON.parse(req.body.conditionJson);
    let username = conditionJson.username;
    let password = conditionJson.password;
    //查询数据库user表
    db.collection('users').findOne({'username': username, 'password': password}).then(document => {
        if (document) {
            req.session.username = username;
            res.send({
                success: true,
                message: "登录成功",
                status: 0,
            });
        } else {
            res.send({
                success: false,
                message: '用户名或密码不存在！',
                status: -1,
            });
        }
    });
};

/**
 * 验证码
 * @param req
 * @param res
 * @param next
 * @return {Promise<void>}
 */
let verify = async (req, res, next) => {
    let email = req.query.email;
    let verifyCode = nodeEmail.verifyCode;
    //验证码也邮箱存入session
    req.session.email = email;
    req.session.verifyCode = verifyCode;

    let options = {
        from: "bidding-system<1490814083@qq.com>", // sender address
        to: email, // list of receivers
        subject: "邮箱验证码", // Subject line
        text: `验证码：${verifyCode}`, // plain text body
    };
    await nodeEmail.transporter.sendMail(options).then(result => {
        res.send({
            msg: "验证码发送成功",
            status: 0,
            verifyCode: verifyCode
        })
    }).catch(err => {
        console.log(`验证码发送失败${err}`);
        res.send({
            msg: "验证码发送失败",
            status: -1
        })
    });
};

/**
 * 获取当前登录用户信息
 * @param req
 * @param res
 * @param next
 * @return {Promise<void>}
 */
let getUser = async (req, res, next) => {
    if (req.session.username) {
        res.send({
            message: "获取用户信息成功",
            status: 0,
            userInfo: {
                username: req.session.username
            }
        })
    } else {
        res.send({
            message: "获取用户信息失败",
            status: -1
        })
    }
};

/**
 * 找回密码
 * @param req
 * @param res
 * @param next
 * @return {Promise<void>}
 */
let findPassword = async (req, res, next) => {
    const db = global.getDB();
    //解析req.body并更新MongoDB数据库：user表
    let conditionJson = JSON.parse(req.body.conditionJson);
    let username = conditionJson.username;
    let password = conditionJson.password;
    let verifyCode = conditionJson.verifyCode;
    let email = conditionJson.email;
    if (verifyCode === req.session.verifyCode && email === req.session.email) {
        try {
            db.collection('users').updateOne({"username": username}, {$set: {"password": password}});
            res.send({
                message: "密码更新成功",
                status: 0
            })
        } catch (e) {
            console.log(e);
            res.send({
                message: "密码更新失败",
                status: -1
            })
        }
    } else {
        res.send({
            message: "验证码错误",
            status: -1
        })
    }
};

module.exports = {
    register,
    login,
    verify,
    getUser,
    findPassword
};